package com.multysite.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import com.multysite.entity.News;
import com.multysite.model.NewsModel;

public class RecentViewHelper {

	private static String cachePrefix = "recentViewCache_";
	private static boolean isRegisted = false;
	private static Cache cache = null;

	public static void initCache() {
		if (!isRegisted) {
			isRegisted = true;
			try {
				cache = CacheManager.getInstance().getCacheFactory()
						.createCache(Collections.emptyMap());
			} catch (CacheException e) {
				isRegisted = false;
			}
		}
	}

	@SuppressWarnings("unchecked")
	public static List<News> getRecentView() {
		initCache();
		String prefix = cachePrefix;
		boolean cached = false;
		List<News> result = new ArrayList<News>();
		if (cache != null) {
			try {
				result = (ArrayList<News>) cache.get(prefix);
				if (result != null && result.size() > 0) {
					cached = true;
				}
			} catch (Exception e) {
				cached = false;
			}
			if (cached) {
				if (result.size() >= 11) {
					NewsModel model = new NewsModel();
					model.setLimit(10);
					model.setPage(1);
					model.prepareList();
					if (model.getListResult().size() > 0) {
						result = model.getListResult();
					}
					cache.put(prefix, result);
				}
			}
		}
		if (!cached) {
			NewsModel model = new NewsModel();
			model.setLimit(10);
			model.setPage(1);
			model.prepareList();
			if (model.getListResult().size() > 0) {
				result = model.getListResult();
				cache.put(prefix, result);
			} else {
				result = new ArrayList<News>();
			}

		}
		return result;
	}

	@SuppressWarnings("unchecked")
	public static void addRecentView(News tub) {
		List<News> recentView = getRecentView();
		for (int i = 0; i < recentView.size(); i++) {
			if (recentView.get(i).getAlias().equals(tub.getAlias())) {
				recentView.remove(i);
			}
		}
		if (recentView.size() >= 10) {
			recentView.remove(0);
		}
		recentView.add(tub);
		initCache();
		cache.put(cachePrefix, recentView);
	}
}
